package com.cqhilink.api.common.utils;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.cqhilink.api.common.utils.date.DateStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 将Office文档转换为PDF、html
 *
 * @author 王镇
 * @create 2017-10-09 18:24
 */
public class Doc2HtmlUtil {

    private static Doc2HtmlUtil doc2HtmlUtil;
    public Logger logger = LoggerFactory.getLogger(Doc2HtmlUtil.class);

    /**
     * 获取Doc2HtmlUtil实例
     */
    public static synchronized Doc2HtmlUtil getDoc2HtmlUtilInstance() {
        if (doc2HtmlUtil == null) {
            doc2HtmlUtil = new Doc2HtmlUtil();
        }
        return doc2HtmlUtil;
    }

    /**
     * 测试main方法
     *
     * @param args
     */

    public static void main(String[] args) throws IOException {

//        File inputFile = new File("C:\\Users\\王镇\\Desktop\\A5系统对接数据表.xlsx");
//
//        File outputFile = new File("C:\\Users\\王镇\\Desktop\\A5系统对接数据表.pdf");
//
//        DOC2PDFUtil dp=new DOC2PDFUtil(inputFile,outputFile);
//        Doc2HtmlUtil coc2HtmlUtil = getDoc2HtmlUtilInstance();
//        File file = null;
//        FileInputStream fileInputStream = null;
//
//        file = new File("D:\\Tools\\Apache_OpenOffice\\jodconverter-2.2.2\\lib\\B.docx");
//        fileInputStream = new FileInputStream(file);
////      coc2HtmlUtil.file2Html("192.168.0.187",8100,fileInputStream, "D:\\Tools\\Apache_OpenOffice\\jodconverter-2.2.2\\lib","docx");
//        String pdfFileName = coc2HtmlUtil.file2pdf("192.168.0.187", 8100, fileInputStream, "D:\\Tools\\Apache_OpenOffice\\jodconverter-2.2.2\\lib\\doc", "docx");
//        System.out.println("pdfFileName=" + pdfFileName);
//        Doc2HtmlUtil.office2PDF("D:\\\\Tools\\\\Apache_OpenOffice\\\\jodconverter-2.2.2\\\\lib\\\\A5.xlsx","D:\\\\Tools\\\\Apache_OpenOffice\\\\jodconverter-2.2.2\\\\lib\\\\A5.pdf");

    }

    /**
     * 转换文件成pdf (备注：不建议Excel问pdf，表格会错位)
     *
     * @param host                openoffice服务器地址
     * @param port                openoffice服务器端口
     * @param fromFileInputStream
     * @param toFilePath
     * @param type
     * @return
     * @throws IOException
     */
    public String file2pdf(String host, int port, InputStream fromFileInputStream, String toFilePath, String type) throws IOException {
        logger.info("file2pdf输入参数 host:{},host:{},toFilePath:{},type:{}", host, port, toFilePath, type);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYY_MM_DD_HH_MM_SS_EN_COMPACT.getValue());
        String timesuffix = sdf.format(date);
        String docFileName = null;
        String pdfFileName = null;
        if ("doc".equals(type)) {
            docFileName = "doc_" + timesuffix + ".doc";
            pdfFileName = "doc_" + timesuffix + ".pdf";
        } else if ("docx".equals(type)) {
            docFileName = "docx_" + timesuffix + ".docx";
            pdfFileName = "docx_" + timesuffix + ".pdf";
        } else if ("xlsx".equals(type)) {
            docFileName = "xlsx_" + timesuffix + ".xlsx";
            pdfFileName = "xlsx_" + timesuffix + ".pdf";
        } else if ("xls".equals(type)) {
            docFileName = "xls_" + timesuffix + ".xls";
            pdfFileName = "xls_" + timesuffix + ".pdf";
        } else if ("ppt".equals(type)) {
            docFileName = "ppt_" + timesuffix + ".ppt";
            pdfFileName = "ppt_" + timesuffix + ".pdf";
        } else {
            return null;
        }

        logger.info("返回的 pdfFileName:{}", pdfFileName);
        File htmlOutputFile = new File(toFilePath + File.separatorChar + pdfFileName);
        File docInputFile = new File(toFilePath + File.separatorChar + docFileName);
        File file = new File(toFilePath);


        // 如果文件夹不存在，就创建文件夹
        if (!file.exists()){
//            System.out.println("===========os.name:"+System.getProperties().getProperty("os.name"));
//            System.out.println("===========file.separator:"+System.getProperties().getProperty("file.separator"));

            this.isWin(file);
            file.mkdirs();
        }

        if (htmlOutputFile.exists())
            htmlOutputFile.delete();
        htmlOutputFile.createNewFile();
        if (docInputFile.exists())
            docInputFile.delete();
        docInputFile.createNewFile();
        /**
         * 由fromFileInputStream构建输入文件
         */
        try {
            OutputStream os = new FileOutputStream(docInputFile);
            int bytesRead = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

            // 关闭输出流
            os.close();
            // 关闭输入流
            fromFileInputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
        try {
            connection.connect();
            // convert
//            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            converter.convert(docInputFile, htmlOutputFile);
        } catch (ConnectException e) {
            logger.info("文件转换出错，请检查OpenOffice服务是否启动。");
        } finally {
            connection.disconnect();
            // 转换完之后删除word文件
            docInputFile.delete();
            logger.info("文件转换成PDF完成");
        }
        return pdfFileName;
    }

//    public static int office2PDF(String sourceFile, String destFile) {
//        try {
//            File inputFile = new File(sourceFile);
//            if (!inputFile.exists()) {
//                return -1;// 找不到源文件, 则返回-1
//            }
//
//            // 如果目标路径不存在, 则新建该路径
//            File outputFile = new File(destFile);
//            if (!outputFile.getParentFile().exists()) {
//                outputFile.getParentFile().mkdirs();
//            }
//
//            String OpenOffice_HOME = "./opt/openoffice4/";//这里是OpenOffice的安装目录, 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的
//            // 如果从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'
////            if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {
////                OpenOffice_HOME += "\\";
////            }
//            // 启动OpenOffice的服务
//            String command = OpenOffice_HOME
//                    + "program/soffice --headless --accept=\"socket,host=192.168.0.187,port=8100;urp;\" --nofirststartwizard&";
//            Process pro = Runtime.getRuntime().exec(command);
//            // connect to an OpenOffice.org instance running on port 8100
//            OpenOfficeConnection connection = new SocketOpenOfficeConnection(
//                    "192.168.0.187", 8100);
//            connection.connect();
//
//            // convert
//            DocumentConverter converter = new OpenOfficeDocumentConverter(
//                    connection);
//            converter.convert(inputFile, outputFile);
//
//            // close the connection
//            connection.disconnect();
//            // 关闭OpenOffice服务的进程
//            pro.destroy();
//
//            return 0;
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            return -1;
//        } catch (ConnectException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return 1;
//    }

    /**
     * 转换文件成html (备注：建议Excel转换为html)
     *
     * @param host                openoffice服务器地址
     * @param port                openoffice服务器端口
     * @param fromFileInputStream 输入文件流
     * @param toFilePath          文件存放地址
     * @param type
     * @return
     * @throws IOException
     */
    public String file2Html(String host, int port, InputStream fromFileInputStream, String toFilePath, String type) throws IOException {
        logger.info("file2Html输入参数 host:{},host:{},toFilePath:{},type:{}", host, port, toFilePath, type);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYY_MM_DD_HH_MM_SS_EN_COMPACT.getValue());
        String timesuffix = sdf.format(date);
        String docFileName = null;
        String htmFileName = null;
        if ("doc".equals(type)) {
            docFileName = "doc_" + timesuffix + ".doc";
            htmFileName = "doc_" + timesuffix + ".html";
        } else if ("docx".equals(type)) {
            docFileName = "docx_" + timesuffix + ".docx";
            htmFileName = "docx_" + timesuffix + ".html";
        } else if ("xls".equals(type)) {
            docFileName = "xls_" + timesuffix + ".xls";
            htmFileName = "xls_" + timesuffix + ".html";
        } else if ("xlsx".equals(type)) {
            docFileName = "xlsx_" + timesuffix + ".xlsx";
            htmFileName = "xlsx_" + timesuffix + ".html";
        } else if ("ppt".equals(type)) {
            docFileName = "ppt_" + timesuffix + ".ppt";
            htmFileName = "ppt_" + timesuffix + ".html";
        } else {
            return null;
        }

        logger.info("返回的 htmFileName:{}", htmFileName);
        File htmlOutputFile = new File(toFilePath + File.separatorChar + htmFileName);
        File docInputFile = new File(toFilePath + File.separatorChar + docFileName);

        File file = new File(toFilePath);
        // 如果文件夹不存在，就创建文件夹
        if (!file.exists()){
            this.isWin(file);
            file.mkdirs();
        }

        if (htmlOutputFile.exists())
            htmlOutputFile.delete();
        htmlOutputFile.createNewFile();
        if (docInputFile.exists())
            docInputFile.delete();
        docInputFile.createNewFile();
        /**
         * 由fromFileInputStream构建输入文件
         */
        try {
            OutputStream os = new FileOutputStream(docInputFile);
            int bytesRead = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

            os.close();
            fromFileInputStream.close();
        } catch (IOException e) {
        }

        OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
        try {
            connection.connect();
            // convert
//            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            converter.convert(docInputFile, htmlOutputFile);
        } catch (ConnectException e) {
            System.err.println("文件转换出错，请检查OpenOffice服务是否启动。");
        } finally {
            connection.disconnect();
            // 转换完之后删除word文件
            docInputFile.delete();
            logger.info("文件转换成Html完成");
        }
        return htmFileName;
    }

    /**
     * 判断当前服务器是什么系统
     * @param file
     */
    private void isWin(File file){
        String ossystem = System.getProperty("os.name");
        logger.info("当前操作系统为：{}",ossystem);
        if(!ossystem.toLowerCase().startsWith("win")){
            //设置写权限，windows下不用此语句
            file.setWritable(true, false);
        }
    }
}
